package com.asset.dispoal.file.evidenceRecognition.service.commom;

import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.asset.dispoal.business.bsAgreement.domain.db.mapper.AgreementMapper;
import com.asset.dispoal.business.bsEvidenceRecognition.domain.db.entity.EvidenceTypeSimpleDo;
import com.asset.dispoal.business.bsEvidenceRecognition.domain.db.entity.MatchSuccessEvidence;
import com.asset.dispoal.business.bsEvidenceRecognition.domain.db.entity.RemoveEvidenceContract;
import com.asset.dispoal.business.bsEvidenceRecognition.domain.db.mapper.BusinessDataManageMapper;
import com.asset.dispoal.business.bsEvidenceRecognition.domain.redis.dto.RedisMergeDTO;
import com.asset.dispoal.business.merge.domain.db.entity.BsMergeDownload;
import com.asset.dispoal.business.merge.domain.db.entity.ConfItemDetailDo;
import com.asset.dispoal.business.merge.domain.db.entity.ConfItemDo;
import com.asset.dispoal.business.merge.domain.db.mapper.MergeDownloadMapper;
import com.asset.dispoal.file.agreementCaseData.domain.db.entity.FileAgreement;
import com.asset.dispoal.file.agreementCaseData.domain.db.mapper.FileAgreementMapper;
import com.asset.dispoal.file.evidenceRecognition.domain.dto.ContractNo;
import com.asset.dispoal.file.evidenceRecognition.dto.MergeEvidenceDownloadRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.data.redis.RedisProperties;
import org.springframework.core.env.Environment;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import tech.mhuang.pacebox.core.compress.DynamicRenameFile;
import tech.mhuang.pacebox.core.compress.RenameFile;
import tech.mhuang.pacebox.core.date.DateTimeUtil;
import tech.mhuang.pacebox.core.ddd.BaseCommand;
import tech.mhuang.pacebox.core.exception.BusinessException;
import tech.mhuang.pacebox.core.file.FileUtil;
import tech.mhuang.pacebox.core.id.BaseIdeable;
import tech.mhuang.pacebox.core.io.IOUtil;
import tech.mhuang.pacebox.core.util.CollectionUtil;
import tech.mhuang.pacebox.core.util.StringUtil;
import tech.mhuang.pacebox.core.util.ZipUtil;
import tech.mhuang.pacebox.springboot.core.entity.RequestModel;
import tech.mhuang.pacebox.springboot.core.local.GlobalHeaderThreadLocal;
import tech.mhuang.pacebox.springboot.core.rest.SingleRestTemplate;
import tech.mhuang.pacebox.springboot.protocol.Result;
import tech.mhuang.pacebox.springboot.redis.commands.IRedisExtCommands;

import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.file.Files;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;

@Component
@Slf4j
public class DownloadMergeEvidenceCommand implements BaseCommand<MergeEvidenceDownloadRequest, Result> {

    @Autowired
    private BaseIdeable<String> ideable;

    @Autowired
    private Environment environment;

    @Autowired
    private MergeDownloadMapper mergeDownloadMapper;

    @Autowired
    private SingleRestTemplate singleRestTemplate;

    @Autowired
    private IRedisExtCommands redisExtCommands;

    @Autowired
    private RedisProperties redisProperties;

    @Autowired
    FileAgreementMapper fileAgreementMapper;

    @Autowired
    private BusinessDataManageMapper businessDataManageMapper;

    @Autowired
    private AgreementMapper agreementMapper;


    private BsMergeDownload initBuild(MergeEvidenceDownloadRequest request) {
        BsMergeDownload mergeDownload = new BsMergeDownload();
        mergeDownload.setId(ideable.generateId());
        mergeDownload.setSubmitTime(DateTimeUtil.currentDate());
        mergeDownload.setCreateUser(GlobalHeaderThreadLocal.getOrException().getUserId());
        mergeDownload.setMergeName(request.getMergeName());
        mergeDownload.setMergeType(request.getMergeType());
        mergeDownload.setDownloadType(request.getDownloadType());
        mergeDownload.setAddPageNum(request.getAddPageNum());
        mergeDownload.setMode(request.getMode());
        mergeDownload.setDownloadFileName(request.getDownloadFileName());
        mergeDownload.setEvidenceConfId(request.getEvidenceConfId());
        mergeDownload.setAssetInstBatchId(request.getAssetInstBatchId());
        return mergeDownload;
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public Result execute(MergeEvidenceDownloadRequest request) {
        BsMergeDownload mergeDownload = initBuild(request);
        LocalDate now = LocalDate.now();
        String year = String.valueOf(now.getYear());
        String month = String.valueOf(now.getMonthValue());
        String day = String.valueOf(now.getDayOfMonth());

        List<String> agreementIdList;
        //选择打包
        if (StringUtil.equals(request.getMode(), "1")) {
            agreementIdList = request.getContractIdList();
            //条件打包
        } else if (StringUtil.equals(request.getMode(), "2")) {
            try {

                List<ContractNo> contractNoList = EasyExcel.read(request.getFile().getInputStream()).head(ContractNo.class).sheet().doReadSync();
                List<String> contractNoStrList = contractNoList.stream().map(ContractNo::getContractNo).collect(Collectors.toList());
                agreementIdList = agreementMapper.queryAgreementByNo(contractNoStrList, request.getAssetInstBatchId());

            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        } else {
            agreementIdList = agreementMapper.queryAgreementIdByCaseIds(request.getCaseIdList());
        }
        if (CollectionUtil.isEmpty(agreementIdList)) {
            return Result.faild("导出的合同在系统中不存在");
        }
        if (StringUtil.equals(request.getMode(), "2")) {
            try {
                FileAgreement fileAgreement = new FileAgreement();
                fileAgreement.setId(ideable.generateId());
                fileAgreement.setFilePath(environment.getProperty("file.evidence.url") + "/custdownload/" + year + "/" + month + "/" + day + "/");
                fileAgreement.setFileName(ideable.generateId() + "_" + request.getFile().getName());
                fileAgreement.setFileOriginalName(request.getFile().getName());
                File copyFile = new File(fileAgreement.getFilePath());
                if (!copyFile.exists()) {
                    FileUtil.createDirectory(copyFile, true);
                }
                request.getFile().transferTo(new File(fileAgreement.getFilePath() + fileAgreement.getFileName()));
                mergeDownload.setFileId(fileAgreement.getId());
                fileAgreementMapper.insert(fileAgreement);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        //查询证据、数据进行组装
        JSONObject mergeJsonData = packMergeEvidence(request, agreementIdList);

        String docUrl = environment.getProperty("file.evidence.url");
        //本地打包
        if ("2".equals(request.getDownloadType())) {
            JSONArray merges = mergeJsonData.getJSONArray("merges");
            String fileUrl = "/custdownload/" + year + "/" + month + "/" + day + "/" + ideable.generateId() + ".zip";
            localMerge(merges, docUrl + fileUrl);
            mergeDownload.setState("1");
            mergeDownload.setDownloadFileUrl(fileUrl);
            mergeDownload.setCompleteTime(DateTimeUtil.currentDate());
        } else {
            String mergeRecordPath = docUrl + "/merge/record/" + year + "/" + month + "/" + day + "/";
            String mergeResultPath = docUrl + "/merge/result/" + year + "/" + month + "/" + day + "/";
            mergeJsonData.put("mergeRecordPath", mergeRecordPath);
            mergeJsonData.put("mergeResultPath", mergeResultPath);
            remoteMerge(mergeJsonData, mergeDownload.getId());
            mergeDownload.setState("2");
            mergeDownload.setCompleteTime(DateTimeUtil.currentDate());
        }
        mergeDownloadMapper.insert(mergeDownload);
//        if(CollectionUtil.isNotEmpty(request.getEvidenceTypeIdList())){
//            mergeDownloadMapper.insertEvidenceType(mergeDownload.getId() ,request.getEvidenceTypeIdList());
//        }
        if (CollectionUtil.isNotEmpty(agreementIdList)) {
            mergeDownloadMapper.insertAgreement(mergeDownload.getId(), agreementIdList);
        }
        return Result.ok();
    }

    /**
     * 远程打包
     *
     * @param mergeJsonData 打包封装的数据
     */
    private void remoteMerge(JSONObject mergeJsonData, String id) {
        redisExtCommands.hset(6, "merge_before", id, mergeJsonData);
        RedisMergeDTO dto = new RedisMergeDTO();
        dto.setDb("6");
        dto.setId("1");
        dto.setKey(id);
        dto.setHost(redisProperties.getHost());
        dto.setPort(redisProperties.getPort());
        dto.setPasswd(redisProperties.getPassword());
        dto.setMergeFile("merge_before");
        dto.setErrorKey("merge_err_key");
        dto.setNotifyKey("merge_notify_key");
        dto.setServerUrl(environment.getProperty("evidence.merge.notify_url"));
        RequestModel<String> requestModel = new RequestModel<String>() {
        };
        requestModel.setUrl(environment.getProperty("evidence.merge.send_url"));
        requestModel.setMethod(HttpMethod.POST);
        requestModel.setParams(dto);
        singleRestTemplate.request(requestModel);
    }

    /**
     * 证据种类打包
     *
     * @param mergeJsonData              需要组装成的数据
     * @param request                    请求组装的参数
     * @param matchSuccessEvidenceList   能匹配上的证据集
     * @param entrySet                   身份证分离的数据集
     * @param removeEvidenceContractList 删除的证据
     */
    private void makeEvidenceType(JSONObject mergeJsonData, MergeEvidenceDownloadRequest request, List<MatchSuccessEvidence> matchSuccessEvidenceList, Set<Map.Entry<String, List<Map<String, String>>>> entrySet, List<RemoveEvidenceContract> removeEvidenceContractList) {
        //1：先循环人
        //2：根据人循环证据种类
        //3：根据人的证据种类查找对应的证据
        //4：根据证据的种类类型确认拼接方式
        //5: 保存识别的证据和种类数据信息
        List<EvidenceTypeSimpleDo> simpleDoList = businessDataManageMapper.queryByEvidenceTypeIdList(request.getAssetInstBatchId(), request.getEvidenceTypeIdList());
        Map<String, List<MatchSuccessEvidence>> matchSuccessEvidenceMap = matchSuccessEvidenceList.stream().collect(Collectors.groupingBy(MatchSuccessEvidence::getEvidenceTypeId));
        for (Map.Entry<String, List<Map<String, String>>> entry : entrySet) {
            String idCard = entry.getKey();
            List<Map<String, String>> agreementList = entry.getValue();
            JSONObject jsonObj = new JSONObject();
            mergeJsonData.getJSONArray("merges").add(jsonObj);
            jsonObj.put("no", idCard);
            jsonObj.put("fileName", agreementList.get(0).get("borrowerName") + "-" + agreementList.get(0).get("borrowerIdcard"));
            JSONArray fileDataArray = new JSONArray();
            jsonObj.put("fileData", fileDataArray);
            for (EvidenceTypeSimpleDo simpleDo : simpleDoList) {
                JSONObject fileDataObj = new JSONObject();
                fileDataArray.add(fileDataObj);
                fileDataObj.put("classifyCode", simpleDo.getId());
                fileDataObj.put("classifyName", simpleDo.getName());
                JSONArray typeArr = new JSONArray();
                JSONObject typeObj = new JSONObject();
                typeArr.add(typeObj);
                fileDataObj.put("types", typeArr);
                typeObj.put("processMode", "1");
                typeObj.put("isMerge", "0");
                typeObj.put("typeCode", simpleDo.getId());
                typeObj.put("typeName", simpleDo.getName());
                typeObj.put("files", new JSONArray());
                //循环匹配上的案件证据查找对应的人相关的证据，然后根据证据种类级别来进行存储。如果证据是三级则只保留一份，
                List<MatchSuccessEvidence> matchSuccessEvidenceTypeList = matchSuccessEvidenceMap.getOrDefault(simpleDo.getId(), Collections.EMPTY_LIST);
                for (MatchSuccessEvidence matchSuccessEvidence : matchSuccessEvidenceTypeList) {
                    Boolean result = Boolean.FALSE;
                    List<Map<String, String>> agreementMatchDataList = new ArrayList<>();
                    //无需匹配的保存
                    if (StringUtil.isEmpty(matchSuccessEvidence.getAlias())) {
                        result = true;
                        agreementMatchDataList.addAll(agreementList);
                    } else {
                        //关联上条件的匹配
                        try {
                            List<Map<String, String>> agreementMatchList = agreementList.parallelStream().filter(agreement -> {
                                try {
                                    return agreement.get(matchSuccessEvidence.getAlias()).equals(matchSuccessEvidence.getResult());
                                } catch (Exception e) {
                                    return false;
                                }
                            }).collect(Collectors.toList());
                            if (CollectionUtil.isNotEmpty(agreementMatchList)) {
                                result = true;
                                agreementMatchDataList.addAll(agreementMatchList);
                            }
                        } catch (Exception ignore) {
                        }
                    }

                    //匹配上的证据并且添加是否已经删除对应证据、如果此证据全部删除了则返回false
                    if (result) {
                        Set<String> removeContractSet = removeEvidenceContractList.stream().filter(removeEvidenceContract -> removeEvidenceContract.getEvidenceId().equals(matchSuccessEvidence.getEvidenceId())).map(RemoveEvidenceContract::getContractId).collect(Collectors.toSet());
                        Optional<Map<String, String>> agreementMatchOptional = agreementMatchDataList.stream().filter(agreementMatchData -> !removeContractSet.contains(agreementMatchData.get("contractId"))).findFirst();
                        if (agreementMatchOptional.isPresent()) {
                            JSONObject fileObj = new JSONObject();
                            fileObj.put("id", matchSuccessEvidence.getEvidenceId());
                            fileObj.put("no", agreementMatchOptional.get().get("no"));
                            //文件路径
                            fileObj.put("filepath", environment.getProperty("file.evidence.url") + "/" + matchSuccessEvidence.getFileUrl());
                            typeObj.getJSONArray("files").add(fileObj);
                        }
                    }
                }
            }
        }
    }

    private JSONObject packMergeEvidence(MergeEvidenceDownloadRequest request, List<String> agreementIdList) {
        //查询批次下全部匹配上的证据
        List<MatchSuccessEvidence> matchSuccessEvidenceList = businessDataManageMapper.queryMatchSuccessEvidence(request.getAssetInstBatchId(), null, null);
        //查询批次下全部删除的证据id和合同id
        List<RemoveEvidenceContract> removeEvidenceContractList = businessDataManageMapper.queryRemoveEvidenceContractByAgreementIdList(request.getAssetInstBatchId(), agreementIdList);
        //匹配的条件
        List<Map<String, String>> mapList = businessDataManageMapper.queryDataDetail(request.getAssetInstBatchId());
        //搜索的数据集
        List<Map<String, String>> queryResult = businessDataManageMapper.queryResultByContractId(request.getAssetInstBatchId(), mapList, agreementIdList);
        Map<String, List<Map<String, String>>> groupedMap = queryResult.stream().collect(Collectors.groupingBy(e -> e.get("borrowerIdcard")));
        Set<Map.Entry<String, List<Map<String, String>>>> entrySet = groupedMap.entrySet();
        JSONObject mergeJsonData = new JSONObject();
        mergeJsonData.put("isZip", request.getDownloadType());
        mergeJsonData.put("usePageNum",request.getAddPageNum());
        mergeJsonData.put("merges", new JSONArray(entrySet.size()));
        if ("1".equals(request.getMergeType())) {
            makeEvidenceCommonConf(mergeJsonData, request, matchSuccessEvidenceList, entrySet, removeEvidenceContractList);
        } else {
            makeEvidenceType(mergeJsonData, request, matchSuccessEvidenceList, entrySet, removeEvidenceContractList);
        }
        return mergeJsonData;
    }

    private JSONObject assembly(ConfItemDetailDo confItemDetailDto) {
        JSONObject json3 = new JSONObject();
        json3.put("typeCode", confItemDetailDto.getTypeCode());
        json3.put("typeName", confItemDetailDto.getTypeName());
        json3.put("processMode", confItemDetailDto.getProcessMode());
        json3.put("isMerge", confItemDetailDto.getIsMerge());
        return json3;
    }

    /**
     * 合并封装通用配置
     *
     * @param mergeJsonData              需要组装成的数据
     * @param request                    请求组装的参数
     * @param matchSuccessEvidenceList   能匹配上的证据集
     * @param entrySet                   身份证分离的数据集
     * @param removeEvidenceContractList 删除的证据
     */
    private void makeEvidenceCommonConf(JSONObject mergeJsonData, MergeEvidenceDownloadRequest request, List<MatchSuccessEvidence> matchSuccessEvidenceList, Set<Map.Entry<String, List<Map<String, String>>>> entrySet, List<RemoveEvidenceContract> removeEvidenceContractList) {
        List<ConfItemDo> confItemDoList = mergeDownloadMapper.findConfItemDetailById(request.getEvidenceConfId(), request.getAppointId());
        if (CollectionUtil.isEmpty(confItemDoList)) {
            throw new BusinessException(Result.SYS_FAILD, "证据打包分类未配置");
        }
        List<String> evidenceTypeIdList = mergeDownloadMapper.findTypeIds(request.getEvidenceConfId(), request.getAppointId());
        if (CollectionUtil.isEmpty(evidenceTypeIdList)) {
            throw new BusinessException(Result.SYS_FAILD, "证据打包分类中的种类未匹配");
        }
        Map<String, List<MatchSuccessEvidence>> matchSuccessEvidenceMap = matchSuccessEvidenceList.stream().collect(Collectors.groupingBy(MatchSuccessEvidence::getEvidenceTypeId));

        request.setEvidenceTypeIdList(evidenceTypeIdList);
        for (Map.Entry<String, List<Map<String, String>>> entry : entrySet) {
            String idCard = entry.getKey();
            List<Map<String, String>> agreementList = entry.getValue();
            JSONObject jsonObj = new JSONObject();
            mergeJsonData.getJSONArray("merges").add(jsonObj);
            jsonObj.put("no", idCard);
            jsonObj.put("fileName", agreementList.get(0).get("borrowerName") + "-" + agreementList.get(0).get("borrowerIdcard"));
            JSONArray fileDataArray = new JSONArray();
            jsonObj.put("fileData", fileDataArray);
            for (ConfItemDo confItemDto : confItemDoList) {
                JSONObject fileDataObj = new JSONObject();
                fileDataArray.add(fileDataObj);
                fileDataObj.put("classifyCode", confItemDto.getClassifyCode());
                fileDataObj.put("classifyName", confItemDto.getClassifyName());
                JSONArray typeArr = new JSONArray();
                fileDataObj.put("types", typeArr);
                if ("3".equals(confItemDto.getClassifyItemType())) {
                    //区分 取所有证据的列表并且进行按照合同区分
                    Integer num = 1;
                    for (Map<String, String> agreementData : agreementList) {
                        Set<String> removeEvidenceSet = removeEvidenceContractList.stream().filter(removeEvidenceContract -> removeEvidenceContract.getContractId().equals(agreementData.get("contractId"))).map(RemoveEvidenceContract::getEvidenceId).collect(Collectors.toSet());
                        for (ConfItemDetailDo confItemDetailDto : confItemDto.getConfItemDetailDtoList()) {
                            List<MatchSuccessEvidence> matchSuccessEvidenceTypeList = matchSuccessEvidenceMap.getOrDefault(confItemDetailDto.getTypeId(), Collections.EMPTY_LIST);
                            matchSuccessEvidenceTypeList = matchSuccessEvidenceTypeList.stream().filter(matchSuccessEvidence -> !removeEvidenceSet.contains(matchSuccessEvidence.getEvidenceId())).collect(Collectors.toList());
                            final JSONObject assembly = assembly(confItemDetailDto);
                            assembly.put("typeCode", assembly.get("typeCode") + "_" + num);
                            JSONArray fileArr = new JSONArray();
                            assembly.put("files", fileArr);
                            typeArr.add(assembly);
                            for (MatchSuccessEvidence matchSuccessEvidence : matchSuccessEvidenceTypeList) {
                                boolean result = Boolean.FALSE;
                                //无需匹配的保存
                                try {
                                    if (StringUtil.isEmpty(matchSuccessEvidence.getAlias())) {
                                        result = true;
                                    } else if (agreementData.get(matchSuccessEvidence.getAlias()).equals(matchSuccessEvidence.getResult())) {
                                        result = true;
                                    }
                                } catch (Exception ignore) {

                                }

                                //匹配上的证据并且添加是否已经删除对应证据、如果此证据全部删除了则返回false
                                if (result) {
                                    JSONObject fileObj = new JSONObject();
                                    fileObj.put("id", matchSuccessEvidence.getEvidenceId());
                                    fileObj.put("no", agreementData.get("no"));
                                    //文件路径
                                    fileObj.put("filepath", environment.getProperty("file.evidence.url") + "/" + matchSuccessEvidence.getFileUrl());
                                    fileArr.add(fileObj);
                                }
                            }
                        }
                        num = num + 1;
                    }
                } else {
                    //单一和汇总
                    for (ConfItemDetailDo confItemDetailDto : confItemDto.getConfItemDetailDtoList()) {
                        final JSONObject assembly = assembly(confItemDetailDto);
                        JSONArray fileArr = new JSONArray();
                        assembly.put("files", fileArr);
                        typeArr.add(assembly);
                        for (Map<String, String> agreementData : agreementList) {
                            //剔除合同关联删除的证据项
                            Set<String> removeEvidenceSet = removeEvidenceContractList.stream().filter(removeEvidenceContract -> removeEvidenceContract.getContractId().equals(agreementData.get("contractId"))).map(RemoveEvidenceContract::getEvidenceId).collect(Collectors.toSet());
                            List<MatchSuccessEvidence> matchSuccessEvidenceTypeList = matchSuccessEvidenceMap.getOrDefault(confItemDetailDto.getTypeId(), Collections.EMPTY_LIST);
                            matchSuccessEvidenceTypeList = matchSuccessEvidenceTypeList.stream().filter(matchSuccessEvidence -> !removeEvidenceSet.contains(matchSuccessEvidence.getEvidenceId())).collect(Collectors.toList());
                            //循环证据读取匹配上的
                            for (MatchSuccessEvidence matchSuccessEvidence : matchSuccessEvidenceTypeList) {
                                boolean result = Boolean.FALSE;
                                //无需匹配的保存
                                try {
                                    if (StringUtil.isEmpty(matchSuccessEvidence.getAlias())) {
                                        result = true;
                                    } else if (agreementData.get(matchSuccessEvidence.getAlias()).equals(matchSuccessEvidence.getResult())) {
                                        result = true;
                                    }
                                } catch (Exception ignore) {

                                }
                                //匹配上的证据并且添加是否已经删除对应证据、如果此证据全部删除了则返回false
                                if (result) {
                                    JSONObject fileObj = new JSONObject();
                                    fileObj.put("id", matchSuccessEvidence.getEvidenceId());
                                    fileObj.put("no", agreementData.get("no"));
                                    //文件路径
                                    fileObj.put("filepath", environment.getProperty("file.evidence.url") + "/" + matchSuccessEvidence.getFileUrl());
                                    fileArr.add(fileObj);
                                }
                            }
                            //单一 并且当前当前合同存在证据则跳过
                            if ("1".equals(confItemDto.getClassifyItemType()) && CollectionUtil.isNotEmpty(fileArr)) {
                                break;
                            }
                        }
                    }
                }
            }
        }
    }

    /**
     * 本地打包
     *
     * @param mergesList 打包的数据
     * @param basePath   地址
     */
    private void localMerge(JSONArray mergesList, String basePath) {
        OutputStream os = null;
        try {

            File file = new File(basePath);
            if (!file.getParentFile().exists()) {
                file.getParentFile().mkdirs();
            }
            os = Files.newOutputStream(file.toPath());
            List<DynamicRenameFile> zipDynamicFileDTOList = new ArrayList<>();

            Set<String> fileNameRep = new HashSet<>();

            for (Object item : mergesList) {
                JSONObject itemJsonObj = (JSONObject) item;

                JSONArray fileDataArray = itemJsonObj.getJSONArray("fileData");
                for (Object dataMapObj : fileDataArray) {
                    JSONObject dataMap = (JSONObject) dataMapObj;
                    DynamicRenameFile zipDynamicFileDTO = new DynamicRenameFile();
                    zipDynamicFileDTOList.add(zipDynamicFileDTO);
                    String folder = (String) itemJsonObj.get("fileName");
                    String classifyName = (String) dataMap.get("classifyName");
                    zipDynamicFileDTO.setDirName(folder + "/" + classifyName);
                    zipDynamicFileDTO.setFileList(new ArrayList<>());
                    JSONArray typesList = dataMap.getJSONArray("types");
                    if (CollectionUtil.isNotEmpty(typesList)) {
                        for (Object typeObj : typesList) {
                            JSONObject typeMap = (JSONObject) typeObj;
                            List<Map<String, String>> fileResultList = (List<Map<String, String>>) typeMap.get("files");
                            for (Map<String, String> result : fileResultList) {
                                final String filepath = result.get("filepath");
                                File sourcefile = new File(filepath);
                                String fileName = sourcefile.getName();
                                String contractNo = result.get("no");
                                if (StringUtil.isNotBlank(contractNo)) {
                                    fileName = contractNo + "_" + sourcefile.getName();
                                }
                                //添加成功才写入
                                if (fileNameRep.add(fileName)) {
                                    RenameFile renameFile = DynamicRenameFile.renameFile(fileName, sourcefile);
                                    zipDynamicFileDTO.getFileList().add(renameFile);
                                }
                            }
                        }
                    }
                }
            }

            ZipUtil.toDynamicRenameZip(zipDynamicFileDTOList, os);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            throw new BusinessException(500, e.getMessage());
        } finally {
            IOUtil.close(os);
        }
    }
}